package com.winit.openapi.gfs.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.command.GetByKeyCommand;
import com.winit.common.spi.context.CommandContext;
import com.winit.gfs.spi.GfsOrderServices;
import com.winit.gfs.spi.command.BatchSubmitGfsOrderCommand;
import com.winit.gfs.spi.command.CancelOrderCommand;
import com.winit.gfs.spi.command.EditGfsOrderCommand;
import com.winit.gfs.spi.command.GetSingleFieldCommand;
import com.winit.gfs.spi.command.GfsOrderAcessRecordCommand;
import com.winit.gfs.spi.command.GfsOrderSearchCommand;
import com.winit.gfs.spi.command.GfsOrderSynHistorySearchCommand;
import com.winit.gfs.spi.command.MergeOrderCommand;
import com.winit.gfs.spi.command.OrderStatisticsCommand;
import com.winit.gfs.spi.command.PullGfsOrderCommand;
import com.winit.gfs.spi.command.PullTeapplixOrderCommand;
import com.winit.gfs.spi.command.QueryEbayOrderCommand;
import com.winit.gfs.spi.command.SubmitGfsOrderCommand;
import com.winit.gfs.spi.command.UpdateGfsOrderStatusCommand;
import com.winit.gfs.spi.command.UpdateSellerOrderCodeCommand;
import com.winit.gfs.spi.vo.GfsOrder;
import com.winit.gfs.spi.vo.GfsOrderAccessRecordVo;
import com.winit.gfs.spi.vo.GfsOrderDeliveryVasAttrVo;
import com.winit.gfs.spi.vo.GfsOrderDeliveryVasVo;
import com.winit.gfs.spi.vo.GfsOrderDetail;
import com.winit.gfs.spi.vo.GfsOrderSynHistoryVO;
import com.winit.gfs.spi.vo.GfsResponseMsg;
import com.winit.gfs.spi.vo.OrderStatisticsResult;
import com.winit.gfs.spi.vo.PullGfsOrderVo;
import com.winit.gfs.spi.vo.SubmitGfsOrderVO;
import com.winit.gfs.spi.vo.TeapplixStoreVo;
import com.winit.mms.spi.v2.item.vo.ItemVo;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.DateUtil;
import com.winit.openapi.util.ValidateUtil;

/**
 * 
 * @author zhengbo.huang
 */

@Controller
@RequestMapping(value="/gfs/order")
public class GfsOrderController  extends BaseController{
	
    @Resource
    private GfsOrderServices      gfsOrderServices;
	
    /**
     * 查询第三方同步历史记录
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/querySynHistory")
    public String querySynHistory(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsOrderSynHistorySearchCommand command = new GfsOrderSynHistorySearchCommand();
        Searchable<?> searchable = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            searchable = this.buildSearchablePageParams(json);
        }else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        searchable.addSort(new Sort(Direction.DESC, "CREATED"));
        command.setSearchable(searchable);
        command.setCtx(CommandContext.getContext());
        // 调用接口分页查询订单
        Page<GfsOrderSynHistoryVO> pagelist = gfsOrderServices.queryGfsSynHistory(command);
        if (pagelist != null) {
            Map<String, Object> data = this.getPageParams(pagelist);
            data.put("list", pagelist.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    /**
     * 创建出库单订单(单个和批量)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchCreateOutboundOrder")
    public String batchCreateOutboundOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result = new GfsResponseMsg();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validCreateOutboundOrder(json);
            BatchSubmitGfsOrderCommand batchSubmitGfsOrderCommand = resolveOutboundOrderData(json);
            batchSubmitGfsOrderCommand.setCtx(CommandContext.getContext());
            result = gfsOrderServices.batchSubmitGfsOrder(batchSubmitGfsOrderCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("failedCount", result.getFailNum());
        data.put("dwCount", result.getDwNum());
        data.put("errorMsg", result.getMsg());
        responseMsg.setData(data);
        return SUCCESS;
    } 
    
    /**
     * 人工审核状态直接提交订单 ISP&外仓海(单个&批量)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchCreateDROrder")
    public String batchCreateDROrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result = new GfsResponseMsg();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validHumanReviewIspOutboundOrder(json);
            BatchSubmitGfsOrderCommand batchSubmitGfsOrderCommand = buildHumanReviewIspOutbound(json);
            batchSubmitGfsOrderCommand.setCtx(CommandContext.getContext());
            result = gfsOrderServices.batchSubmitGfsOrder(batchSubmitGfsOrderCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("failedCount", result.getFailNum());
        data.put("dwCount", result.getDwNum());
        data.put("errorMsg", result.getMsg());
        responseMsg.setData(data);
        return SUCCESS;
    } 

    /**
     * 创建ISP订单（单个/批量）
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchCreateISPOrder")
    public String batchCreateISPOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result = new GfsResponseMsg();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validCreateISPOrder(json);
            BatchSubmitGfsOrderCommand command = resolveISPOrderData(json);
            command.setCtx(CommandContext.getContext());
            result = gfsOrderServices.batchSubmitGfsOrder(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("failedCount", result.getFailNum());
        data.put("dwCount", result.getDwNum());
        data.put("errorMsg", result.getMsg());
        responseMsg.setData(data);
        return SUCCESS;
    } 
    
    /**
     * gfs提交出库单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/submitOutboundOrder")
    public String submitOutboundOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            //校验参数
            validSubmitOrder(json);
            //构建解析参数
            GfsOrder order = buildSubmitOrder(json);
            // 构建数据
            SubmitGfsOrderCommand command = new SubmitGfsOrderCommand();
            SubmitGfsOrderVO vo = new SubmitGfsOrderVO();
            command.setVo(vo);
            order.setBpartnerId(Long.valueOf(CommandContext.getContext().getUserId()));
            vo.setOrder(order);
            command.setCtx(CommandContext.getContext());
            vo.setSubmit(buildBooleanValue(json,"isSubmit"));
            vo.setMerge(buildBooleanValue(json,"isMerge"));
            vo.setOrderIdList(buildOrderIdList(json));
            vo.setOrderType(ApiConstant.ORDER_TYPE_OUTBOUND);
            GfsResponseMsg gfsResponseMsg = gfsOrderServices.submitGfsOrder(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("successCount", gfsResponseMsg.getSuccessNum());
            data.put("failedCount", gfsResponseMsg.getFailNum());
            data.put("dwCount", gfsResponseMsg.getDwNum());
            data.put("errorMsg", gfsResponseMsg.getMsg());
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    
    /**
     * 提交gfs订单(ISP)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/submitISPOrder")
    public String submitIspOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            //校验参数
            validSubmitOrder(json);
            //构建解析参数
            GfsOrder order = buildSubmitISPOrder(json);
            // 构建数据
            SubmitGfsOrderCommand command = new SubmitGfsOrderCommand();
            SubmitGfsOrderVO vo = new SubmitGfsOrderVO();
            command.setVo(vo);
            vo.setOrder(order);
            CommandContext ctx = CommandContext.getContext();
            vo.setCtx(ctx);
            vo.getOrder().setBpartnerId(Long.parseLong(ctx.getUserId()));
            vo.setSubmit(buildBooleanValue(json,"isSubmit"));
            vo.setMerge(buildBooleanValue(json,"isMerge"));
            vo.setOrderIdList(buildOrderIdList(json));
            vo.setOrderType(ApiConstant.PRODUCT_CATALOG_ISP);
            GfsResponseMsg gfsResponseMsg = gfsOrderServices.submitGfsOrder(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("successCount", gfsResponseMsg.getSuccessNum());
            data.put("failedCount", gfsResponseMsg.getFailNum());
            data.put("dwCount", gfsResponseMsg.getDwNum());
            data.put("errorMsg", gfsResponseMsg.getMsg());
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/pullTeapplixOrder")
    public String pullTeapplixOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.isNotNull(json, "storeType");
            ValidateUtil.validList(json, "storeList", true);
            PullTeapplixOrderCommand command = new PullTeapplixOrderCommand();
            command.setCtx(CommandContext.getContext());
            command.setStoreType(json.getString("storeType"));
            JSONArray arr = json.getJSONArray("storeList");
            List<TeapplixStoreVo> storeList = new ArrayList<TeapplixStoreVo>();
            for(Object o:arr){
                JSONObject j = (JSONObject) o;
                ValidateUtil.validNotNull(j, "storeKey");
                TeapplixStoreVo storeVo = new TeapplixStoreVo();
                storeVo.setStoreKey(j.getString("storeKey"));
                if(StringUtils.equalsIgnoreCase("ebay", json.getString("storeType")) ||
                        StringUtils.equalsIgnoreCase("amazon", json.getString("storeType"))){
                    ValidateUtil.validNotNull(j, "sellerID");
                    storeVo.setSellerID(j.getString("sellerID"));
                }
                storeList.add(storeVo);
            }
            command.setStoreList(storeList);
            gfsOrderServices.pullTeapplixOrder(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    /**
     * 手工同步gfs订单，暂时只有ebay订单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pullGfsOrder")
    public String pullGfsOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsResponseMsg result;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            // 校验参数
            validPullGfsOrder(json);
            //组装参数
        	List<String> ebayAccounts = new ArrayList<String>();
        	//task#60381 erp用户接口迁移 入参由eBayAccountIds更改为ebayAccounts
            JSONArray gfsOrderList = json.getJSONArray("ebayAccounts");
            for (Object o : gfsOrderList) {
                JSONObject tobj = (JSONObject) o;
                ebayAccounts.add(tobj.getString("ebayAccount"));
            }
            
            String orderDateStart=json.getString("orderDateStart");
            String orderDateEnd=json.getString("orderDateEnd");
            PullGfsOrderVo pullGfsOrderVo = new PullGfsOrderVo();
            pullGfsOrderVo.setEbayAccounts(ebayAccounts);
            if(null !=orderDateStart){
                Date from = DateUtil.parse2Date(orderDateStart, DateUtil.FULL_DATE_STRING);
                pullGfsOrderVo.setOrderDateStart(from);
            }
            if(null != orderDateEnd){
                Date end = DateUtil.parse2Date(orderDateEnd, DateUtil.FULL_DATE_STRING);
                Date now = new Date();
                if(end.after(now)){
                    pullGfsOrderVo.setOrderDateEnd(now);
                }else{
                    pullGfsOrderVo.setOrderDateEnd(end);
                }
            }
            
            PullGfsOrderCommand pullGfsOrderCommand =new PullGfsOrderCommand();
            pullGfsOrderCommand.setCtx(CommandContext.getContext());
            pullGfsOrderCommand.setPullGfsOrderVo(pullGfsOrderVo);
            result = gfsOrderServices.pullGfsOrder(pullGfsOrderCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("sysNum",  result.getSysNum());
        data.put("synMinutes", result.getSynMinutes());
        data.put("msg", result.getMsg());
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 查询gfs订单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        //校验参数
        this.validGfsOrderList(requestMsg);
        //封装参数
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            GfsOrderSearchCommand command =buildSearchCommand(json);
            //调用接口
            Page<GfsOrder> pageGfsOrders=gfsOrderServices.queryGfsOrderPage(command);
            Map<String, Object> data = getPageParams(pageGfsOrders);
            data.put("list", pageGfsOrders.getContent());
            //返回结果参数
            Map<String, Object> pageMap = new HashMap<String, Object>();
            pageMap.put("pageNo", pageGfsOrders.getPageable().getPageNumber());
            pageMap.put("pageSize", pageGfsOrders.getPageable().getPageSize());
            pageMap.put("totalCount", pageGfsOrders.getTotalElements());
            data.put("pageParams", pageMap);
            responseMsg.setData(data);
        }
       
        return SUCCESS;
    }
    
    
    /**
     * 修改GFS卖家订单号
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateSellerOrderCode")
    public String updateSellerOrderCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	   Object obj = requestMsg.getData();
    	   GfsResponseMsg result = new GfsResponseMsg();
    	   if (obj instanceof JSONObject) {
               JSONObject json = (JSONObject) obj;
               // 校验参数
	           ValidateUtil.valid(json, "sellerOrderCode", 30, true);
	           ValidateUtil.valid(json, "gfsOrderId", 10, true);
	           UpdateSellerOrderCodeCommand command=new UpdateSellerOrderCodeCommand();
	           command.setSellerOrderCode(json.getString("sellerOrderCode"));
	           command.setGfsOrderId(json.getLong("gfsOrderId"));
	           command.setCtx(CommandContext.getContext());
	           gfsOrderServices.updateSellerOrderCode(command);
    	   }else{
    		   throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
    	   }
    	   Map<String, Object> data = new HashMap<String, Object>();
           data.put("successCount", result.getSuccessNum());
           data.put("failedCount", result.getFailNum());
           responseMsg.setData(data);
    	   return SUCCESS;
    }
    
    /**
     * 取消发货
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/cancelOrder")
    public String cancelOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	  Object obj = requestMsg.getData();
    	  GfsResponseMsg result = new GfsResponseMsg();
   	   if (obj instanceof JSONObject) {
              JSONObject json = (JSONObject) obj;
              // 校验参数
              validateCancel(json);
              //构建数据
              List<Long> listID=buildOrderIdList(json);
              CancelOrderCommand command=new CancelOrderCommand();
              command.setId(listID);
              command.setCtx(CommandContext.getContext());
              Long successCount=gfsOrderServices.cancelOrderById(command);
              result.setSuccessNum(successCount.intValue());
              result.setFailNum((listID.size()-successCount.intValue()));
   	   }else{
   		   throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
   	   }
   	    Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("failedCount", result.getFailNum());
        responseMsg.setData(data);
	    return SUCCESS;
    }
    
    /**
     * 撤销取消发货
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/resumeOrder")
    public String resumeOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
          Object obj = requestMsg.getData();
          GfsResponseMsg result = new GfsResponseMsg();
       if (obj instanceof JSONObject) {
              JSONObject json = (JSONObject) obj;
              // 校验参数
              validateCancel(json);
              //构建数据
              List<Long> listID=buildOrderIdList(json);
              CancelOrderCommand command=new CancelOrderCommand();
              command.setId(listID);
              command.setCtx(CommandContext.getContext());
              Long successCount=gfsOrderServices.resumeOrderById(command);
              result.setSuccessNum(successCount.intValue());
              result.setFailNum((listID.size()-successCount.intValue()));
       }else{
           throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
       }
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("successCount", result.getSuccessNum());
        data.put("failedCount", result.getFailNum());
        responseMsg.setData(data);
        return SUCCESS;
    }
    
    /**
     * 编辑gfs订单
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/editOrder")
    public String editOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "gfsOrderId");
            
            // 构建数据
            EditGfsOrderCommand command = new EditGfsOrderCommand();
            command.setId(json.getLong("gfsOrderId"));
            if(json.containsKey("orderType")){
                command.setOrderType(json.getString("orderType"));
            }
            GfsOrder gfs = gfsOrderServices.editGfsOrderByid(command);
            Map<String, Object> data = buildEditOrder(gfs);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    @RequestMapping(value = "/mergeOrder")
    public String mergeOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "gfsOrderList");
            ValidateUtil.validList(json, "gfsOrderList");
            
            MergeOrderCommand command = new MergeOrderCommand();
            command.setCtx(CommandContext.getContext());
            command.setIdList(buildOrderIdList(json));
            if(json.containsKey("orderType")){
                command.setOrderType(json.getString("orderType"));
            }
            List<GfsOrder> orderList = gfsOrderServices.mergeOrder(command);
            Map<String, Object> data = buildMergeOrderReturn(orderList);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
   
    
    private Map<String, Object> buildMergeOrderReturn(List<GfsOrder> orderList) {
        GfsOrder gfsOrder = orderList.get(0);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("gfsOrderId", gfsOrder.getOrderId());
        data.put("buyerUserId", gfsOrder.getBuyerUserId());
        data.put("sellerUserId", gfsOrder.getSellerUserId());
        data.put("status", gfsOrder.getStatus());
        data.put("sellerOrderCode", gfsOrder.getSellerOrderCode());
        data.put("buyerFullname", gfsOrder.getBuyerFullname());
        data.put("buyerEmail", gfsOrder.getBuyerEmail());
        data.put("buyerPhone", gfsOrder.getBuyerPhone());
        data.put("buyerCountry", gfsOrder.getBuyerCountry());
        data.put("buyerState", gfsOrder.getBuyerState());
        data.put("buyerCity", gfsOrder.getBuyerCity());
        data.put("buyerPostCode", gfsOrder.getBuyerPostCode());
        data.put("buyerAddreess", gfsOrder.getBuyerAddreess2());
        data.put("buyerAddreess2", gfsOrder.getBuyerAddreess3());
        
        data.put("ebayTransactionType", gfsOrder.getEbayTransactionType());
        data.put("orderType", gfsOrder.getOrderType());
        data.put("shipperAddrCode", gfsOrder.getShipperAddrCode());
        data.put("winitProductCode", gfsOrder.getWinitProductCode());
        data.put("winitProductName", gfsOrder.getWinitProductName());
        data.put("extent", gfsOrder.getExtent());
        data.put("weight", gfsOrder.getWeight());
        data.put("width", gfsOrder.getWidth());
        data.put("height", gfsOrder.getHeight());
        data.put("doorplateNumbers", gfsOrder.getDoorpLateNumbers());        
        data.put("trackingNo", gfsOrder.getTrackingNo());   
        data.put("platform", gfsOrder.getPlatform());  
        String egdOrder = ApiConstant.IS_ACTIVE_N;
        Date gddTime = null;

        List<GfsOrderDetail> lstGfsOrderDetail = new ArrayList<GfsOrderDetail>();
        List<Map<String,Object>> gfsOrderIdList = new ArrayList<Map<String,Object>>();
        Map<String,Object> orderIdMap = null;
        List<Map<String,Object>> ebayInfoList = new ArrayList<Map<String,Object>>();
        Map<String,Object> ebayInfo = null;
        for(GfsOrder ebayOrder:orderList){
            ebayInfo = new HashMap<String, Object>();
            orderIdMap = new HashMap<String, Object>();
            ebayInfo.put("sellerUserId", ebayOrder.getSellerUserId());
            ebayInfo.put("checkOutDate", ebayOrder.getCheckOutDate());
            ebayInfo.put("paymentDate", ebayOrder.getPaymentDate());
            ebayInfo.put("postageDate", ebayOrder.getPostageDate());
            ebayInfo.put("feedbackSent", ebayOrder.getFeedbackSent());
            ebayInfo.put("feedbackReceive", ebayOrder.getFeedbackReceive());
            ebayInfo.put("paymentReceivedDate", ebayOrder.getPaymentReceivedDate());
            ebayInfo.put("paymentMethod", ebayOrder.getPaymentMethod());
            ebayInfo.put("postedDate", ebayOrder.getPostedDate());
            ebayInfo.put("postageService", ebayOrder.getPostageService());
            ebayInfo.put("lastEmailSent", ebayOrder.getDeliveryDate());//发货时间
            ebayInfo.put("saleDate", ebayOrder.getSaleDate());
            ebayInfo.put("totalAllPrice", ebayOrder.getTotalAllPrice());
            ebayInfo.put("totalPriceCurrency", ebayOrder.getTotalPriceCurrency());
            ebayInfo.put("payPriceCurrency", ebayOrder.getPayPriceCurrency());
            ebayInfo.put("payPrice", ebayOrder.getPayPrice());
            ebayInfo.put("txStoreKey", ebayOrder.getTxStoreKey());  
            ebayInfo.put("txVSAccountID", ebayOrder.getTxVSAccountID());  
            ebayInfo.put("txShipping", ebayOrder.getTxShipping());  
            ebayInfo.put("txTax", ebayOrder.getTxTax());  
            ebayInfo.put("txHandling", ebayOrder.getTxHandling());  
            ebayInfo.put("txDiscount", ebayOrder.getTxDiscount());  
            ebayInfo.put("txInsuranceType", ebayOrder.getTxInsuranceType());
            ebayInfo.put("txCurrency", ebayOrder.getTxCurrency());
            ebayInfo.put("txMemo", ebayOrder.getTxMemo());
            ebayInfo.put("txGiftMessage", ebayOrder.getTxGiftMessage());
            ebayInfo.put("platform", ebayOrder.getPlatform());
            ebayInfo.put("ebayProductList", ebayOrder.getEbayProductList());
            lstGfsOrderDetail.addAll(ebayOrder.getListGfsOrderDetail());
            orderIdMap.put("gfsOrderId", ebayOrder.getOrderId());
            gfsOrderIdList.add(orderIdMap);
            ebayInfoList.add(ebayInfo);
            if(ApiConstant.IS_ACTIVE_Y.equals(ebayOrder.getEgdOrder())){
                egdOrder = ebayOrder.getEgdOrder();
                if(gddTime == null){
                    gddTime = ebayOrder.getGddTimeMax();
                }else if(ebayOrder.getGddTimeMax() != null && ebayOrder.getGddTimeMax().before(gddTime)){
                    gddTime = ebayOrder.getGddTimeMax();
                }
            }
        }
        data.put("gfsOrderList", gfsOrderIdList);
        data.put("listGfsOrderDetail", lstGfsOrderDetail);
        data.put("ebayInfoList", ebayInfoList);
        data.put("gddTime", gddTime);
        data.put("egdOrder", egdOrder);
        
        return data;
   
    }

    /**
     * 
     * 获取订单某个字段的数据列表(去重)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/querySingleFieldList")
    public String querySingleFieldList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {

        Object obj = requestMsg.getData();
        
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            String fieldName = json.getString("fieldName");
            String status=json.getString("status");
            String orderType=json.getString("orderType");
            GetSingleFieldCommand command = new GetSingleFieldCommand();
            command.setBpartnerId(Long.valueOf(CommandContext.getContext().getUserId()));
            command.setFieldName(fieldName);
            command.setOrderType(orderType);
            command.setStatus(status);
            List<String> dataList = gfsOrderServices.querySingleFieldList(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", dataList);
            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    @RequestMapping(value="/addAccessRecord")
    public String addAccessRecord(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	Object obj = requestMsg.getData();
    	if(obj instanceof JSONObject){
    		JSONObject json = (JSONObject) obj;
            //校验参数
    		validAccessRecord(json);
            //构建解析参数
    		GfsOrderAcessRecordCommand command = acessSearchCommand(json);
            // 构建数据
            command.setBpartnerId(Long.valueOf(CommandContext.getContext().getUserId()));
            
            Map<String, Object> data = new HashMap<String, Object>();
            GfsOrderAccessRecordVo vo = gfsOrderServices.getNumber(command);
            data.put("vo", vo);
            responseMsg.setData(data);
    	}else{
    		throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
    	}
    	return SUCCESS;
    }
    
    @RequestMapping(value="/updateOrderQuantity")
    public String updateOrderQuantity(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
    	Object obj = requestMsg.getData();
    	if(obj instanceof JSONObject){
    		JSONObject json = (JSONObject) obj;
    		//校验参数
    		updateOrderQuantityRecord(json);
            //构建解析参数
    		GfsOrderDetail command = updateOrderQuantityCommand(json);
            // 构建数据
    		gfsOrderServices.updateOrderQuantity(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("code", 1);
            responseMsg.setData(data);
    	}else{
    		throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
    	}
    	return SUCCESS;
    }
    
    
    @RequestMapping(value = "/updateGFSOrderStatus")
    public String updateGFSOrderStatus(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "winitOrderNo");
            ValidateUtil.validNotNull(json, "status");
            // 构建解析参数
            UpdateGfsOrderStatusCommand gfsCommand = new UpdateGfsOrderStatusCommand();
            gfsCommand.setWinitOrderCode(json.getString("winitOrderNo"));
            gfsCommand.setStatus(json.getString("status"));
            gfsOrderServices.updateGfsOrderStatus(gfsCommand);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }
    
    
    /**
     * 
     * 订单统计
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getOrderStatistics")
    public String getOrderStatistics(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        OrderStatisticsResult result = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "saleDateStart");
            ValidateUtil.validNotNull(json, "saleDateEnd");
            ValidateUtil.validDateString(json, "saleDateStart", DateUtil.SIMPLE_DATE_STRING);
            ValidateUtil.validDateString(json, "saleDateEnd", DateUtil.SIMPLE_DATE_STRING);
            
            OrderStatisticsCommand command = new OrderStatisticsCommand();
            String saleDateStartStr = json.getString("saleDateStart") + " 00:00:00";
            String saleDateEndStr = json.getString("saleDateEnd") + " 23:59:59";
            Date saleDateStart = DateUtil.parse2Date(saleDateStartStr, DateUtil.FULL_DATE_STRING);
            Date saleDateEnd = DateUtil.parse2Date(saleDateEndStr, DateUtil.FULL_DATE_STRING);
            command.setSaleDateStart(saleDateStart);
            command.setSaleDateEnd(saleDateEnd);
            command.setCtx(CommandContext.getContext());
            
            result = gfsOrderServices.getOrderStatistics(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        responseMsg.setData(result);
        return SUCCESS;
    } 
    
    /**
     * 
     * 订单统计
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryOrderByTidAndIid")
    public String queryOrderByTidAndIid(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        GfsOrder gfsOrder = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "transactionId");
            ValidateUtil.validNotNull(json, "itemId");
            ValidateUtil.validNotNull(json, "sellerUserId");
            
            ValidateUtil.validMaxLength(json, "transactionId", 19);
            ValidateUtil.validMaxLength(json, "itemId", 19);
            
            ValidateUtil.validMustNumber(json, "transactionId");
            ValidateUtil.validMustNumber(json, "itemId");
            
            String transactionId = json.getString("transactionId");
            String itemId = json.getString("itemId");
            String sellerUserId = json.getString("sellerUserId");
            
            QueryEbayOrderCommand command = new QueryEbayOrderCommand();
            command.setCtx(CommandContext.getContext());
            command.setTransactionId(transactionId);
            command.setItemId(itemId);
            command.setSellerUserId(sellerUserId);
            command.setBpartnerId(Long.valueOf(CommandContext.getContext().getUserId()));
            gfsOrder = gfsOrderServices.queryEbayOrderByTidAndIid(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        responseMsg.setData(gfsOrder);
        return SUCCESS;
    }    
    
    @RequestMapping(value = "/matchItem")
    public String matchItem(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        List<ItemVo> itemList = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "customLabel");
            ValidateUtil.validMaxLength(json, "customLabel", 128);
            
            GetByKeyCommand<String> command = new GetByKeyCommand<String>();
            command.setSearchKey(json.getString("customLabel"));
            command.setCtx(CommandContext.getContext());
            itemList = gfsOrderServices.matchItem(command);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        responseMsg.setData(itemList);
        return SUCCESS;
    }
    
    private void validHumanReviewIspOutboundOrder(JSONObject json) {

            ValidateUtil.validNotNull(json, "orderType");
	        if (!json.containsKey("gfsOrderList")) {
	            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "gfsOrderVO");
	        }
	        JSONArray ebaylist = json.getJSONArray("gfsOrderList");
	        if(ebaylist.size() <= 0){
	        	 throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "gfsOrderVO");
	        }
	    }
    
    private GfsOrderDetail updateOrderQuantityCommand(JSONObject json)
    {
    	GfsOrderDetail vo = new GfsOrderDetail();
    	
    	if (ValidateUtil.isNotNull(json, "orderId")) {
            ValidateUtil.validInteger(json, "orderId");
            vo.setOrderId(json.getLong("orderId"));
        }
    	
    	if (ValidateUtil.isNotNull(json, "orderQuantity")) {
            ValidateUtil.validInteger(json, "orderQuantity");
            vo.setOrderQuantity(json.getInteger("orderQuantity"));
        }
    	
    	return vo;
    }
    
    private void validSubmitOrder(JSONObject json)
    {
        // 校验参数
        ValidateUtil.validNotNull(json, "gfsOrderId");
        //ValidateUtil.validNotNull(json, "winitOrderCode");
        ValidateUtil.validNotNull(json, "warehouseCode");
        ValidateUtil.validMaxLength(json, "warehouseCode", 32);
        ValidateUtil.validMaxLength(json, "warehouseName", 32);
        ValidateUtil.validNotNull(json, "deliveryWay");
        //ValidateUtil.validMaxLength(json, "deliveryWay", 32);
        //ValidateUtil.validNotNull(json, "insuranceType");
        //ValidateUtil.validMaxLength(json, "insuranceType", 32);
        ValidateUtil.validNotNull(json, "sellerOrderCode");
        ValidateUtil.validMaxLength(json, "sellerOrderCode", 100);
        ValidateUtil.validNotNull(json, "productList");
    }
    
    
	private void validAccessRecord(JSONObject json)
    {
    	ValidateUtil.validNotNull(json, "status");
    }
	
	private void updateOrderQuantityRecord(JSONObject json)
    {
    	ValidateUtil.validNotNull(json, "orderId");
    	ValidateUtil.validNotNull(json, "orderQuantity");
    }
	
	private BatchSubmitGfsOrderCommand buildHumanReviewIspOutbound(JSONObject json ) {
        BatchSubmitGfsOrderCommand  command  = new BatchSubmitGfsOrderCommand();
        command.setSubmit(buildBooleanValue(json,"isSubmit"));
        command.setOrderType(json.getString("orderType"));
    	List<GfsOrder> gfsOrders = new ArrayList<GfsOrder>();
        JSONArray gfsOrderList = json.getJSONArray("gfsOrderList");
        for (Object o : gfsOrderList) {
        	GfsOrder gfsOrder = new GfsOrder();
        	JSONObject tobj = (JSONObject) o;
        	gfsOrder.setOrderId(tobj.getLong("gfsOrderId"));
        	gfsOrders.add(gfsOrder);
        }
        command.setGfsOrders(gfsOrders);
        return command;
    }
    
    private GfsOrder buildSubmitOrder(JSONObject json) {
        GfsOrder gfsOrder = new GfsOrder();
        gfsOrder.setOrderId(json.getLong("gfsOrderId"));
        gfsOrder.setStatus(json.getString("status"));
        gfsOrder.setWinitProductCode(json.getString("winitProductCode"));
        gfsOrder.setWinitOrderCode(json.getString("winitOrderCode"));
        gfsOrder.setWinitwarehouseID(json.getLong("warehouseID"));
        gfsOrder.setWarehouseCode(json.getString("warehouseCode"));
        gfsOrder.setWarehouseName(json.getString("warehouseName"));
        gfsOrder.setDeliveryWayCode(json.getString("deliveryWay"));
        gfsOrder.setDeliveryWayName(json.getString("deliveryWayName"));
        gfsOrder.setInsuranceType(json.getString("insuranceType"));
        gfsOrder.setSellerUserId(json.getString("sellerUserId"));
        gfsOrder.setBuyerUserId(json.getString("buyerUserId"));
        gfsOrder.setSellerOrderCode(json.getString("sellerOrderCode"));
        gfsOrder.setBuyerFullname(json.getString("buyerFullname"));
        gfsOrder.setBuyerEmail(json.getString("buyerEmail"));
        gfsOrder.setBuyerCountry(json.getString("buyerCountry"));
        gfsOrder.setBuyerPhone(json.getString("buyerPhone"));
        gfsOrder.setBuyerState(json.getString("buyerState"));
        gfsOrder.setBuyerCity(json.getString("buyerCity"));
        gfsOrder.setBuyerPostCode(json.getString("buyerPostCode"));
        gfsOrder.setBuyerAddreess2(json.getString("buyerAddreess1"));
        gfsOrder.setBuyerAddreess3(json.getString("buyerAddreess2"));
        gfsOrder.setDoorpLateNumbers(json.getString("doorplateNumbers"));
        if(ValidateUtil.isNotNull(json, "remark")){
            gfsOrder.setRemark(json.getString("remark"));
        }
        buildVasAndAttr(gfsOrder,json);
        List<GfsOrderDetail> listGfsOrderDetail = new ArrayList<GfsOrderDetail>();
        JSONArray orderList = json.getJSONArray("productList");
        for (Object obj : orderList) {
            JSONObject tmp = (JSONObject) obj;
            GfsOrderDetail detail = new GfsOrderDetail();
            detail.setSku(tmp.getString("productCode"));
            detail.setSpecification(tmp.getString("specifications"));
            detail.setTransactionId(tmp.getString("transactionId"));
            detail.setItemId(tmp.getString("itemId"));
            detail.setItemName(tmp.getString("productName"));
            detail.setItemNameEN(tmp.getString("productNameEn"));
            detail.setOrderQuantity(tmp.getInteger("orderQuantity"));
            if(ValidateUtil.isNotNull(tmp, "quantity")){
            	ValidateUtil.validNotNegativeNumber(tmp, "quantity");
            	detail.setQuantity(tmp.getInteger("quantity"));
            }
            if(ValidateUtil.isNotNull(tmp, "transactionCurrency")){
            	detail.setTransactionCurrency(tmp.getString("transactionCurrency"));
            }
            if(ValidateUtil.isNotNull(tmp, "transactionPrice")){
                ValidateUtil.validNotNegativeNumber(tmp, "transactionPrice");
                ValidateUtil.validatePrecision(tmp, "transactionPrice", 10, 2);
                detail.setTransactionPrice(tmp.getBigDecimal("transactionPrice"));
            }
            if(ValidateUtil.isNotNull(tmp, "goodsLocation")){
                detail.setGoodsLocation(tmp.getString("goodsLocation"));
            }
            if(ValidateUtil.isNotNull(tmp, "reSelect")){
                detail.setReSelect(tmp.getString("reSelect"));
            }
            listGfsOrderDetail.add(detail);
        }
        gfsOrder.setListGfsOrderDetail(listGfsOrderDetail);
        return gfsOrder;
    }
    
    private GfsOrder buildSubmitISPOrder(JSONObject json) {
        GfsOrder gfsOrder = new GfsOrder();
        gfsOrder.setOrderId(json.getLong("gfsOrderId"));
        gfsOrder.setStatus(json.getString("status"));
        gfsOrder.setWinitProductCode(json.getString("winitProductCode"));
        gfsOrder.setWinitProductName(json.getString("winitProductName"));
        gfsOrder.setWinitOrderCode(json.getString("winitOrderCode"));
        gfsOrder.setWinitwarehouseID(json.getLong("warehouseID"));
        gfsOrder.setWarehouseCode(json.getString("warehouseCode"));
        gfsOrder.setWarehouseName(json.getString("warehouseName"));
        gfsOrder.setDeliveryWayCode(json.getString("deliveryWay"));
        gfsOrder.setDeliveryWayName(json.getString("deliveryWayName"));
        gfsOrder.setInsuranceType(json.getString("insuranceType"));
        gfsOrder.setSellerUserId(json.getString("sellerUserId"));
        gfsOrder.setBuyerUserId(json.getString("buyerUserId"));
        gfsOrder.setSellerOrderCode(json.getString("sellerOrderCode"));
        gfsOrder.setBuyerFullname(json.getString("buyerFullname"));
        gfsOrder.setBuyerEmail(json.getString("buyerEmail"));
        gfsOrder.setBuyerCountry(json.getString("buyerCountry"));
        gfsOrder.setBuyerPhone(json.getString("buyerPhone"));
        gfsOrder.setBuyerState(json.getString("buyerState"));
        gfsOrder.setBuyerCity(json.getString("buyerCity"));
        gfsOrder.setBuyerPostCode(json.getString("buyerPostCode"));
        gfsOrder.setBuyerAddreess2(json.getString("buyerAddreess1"));
        gfsOrder.setBuyerAddreess3(json.getString("buyerAddreess2"));
        gfsOrder.setShipperAddrCode(json.getString("sellerAddreessCode"));
        if(ValidateUtil.isNotNull(json, "weight"))
        {
            ValidateUtil.validNotNegativeNumber(json, "weight");
            ValidateUtil.validatePrecision(json, "weight", 10, 4);
            gfsOrder.setWeight(json.getBigDecimal("weight"));
        }
        if(ValidateUtil.isNotNull(json, "extent"))
        {
            ValidateUtil.validNotNegativeNumber(json, "extent");
            ValidateUtil.validatePrecision(json, "extent", 10, 2);
            gfsOrder.setExtent(json.getBigDecimal("extent"));
        }
        if(ValidateUtil.isNotNull(json, "width"))
        {
            ValidateUtil.validNotNegativeNumber(json, "width");
            ValidateUtil.validatePrecision(json, "width", 10, 2);
            gfsOrder.setWidth(json.getBigDecimal("width"));
        }
        if(ValidateUtil.isNotNull(json, "height"))
        {
            ValidateUtil.validNotNegativeNumber(json, "height");
            ValidateUtil.validatePrecision(json, "height", 10, 2);
            gfsOrder.setHeight(json.getBigDecimal("height"));
        }
        if(ValidateUtil.isNotNull(json, "remark")){
            gfsOrder.setRemark(json.getString("remark"));
        }
        List<GfsOrderDetail> listGfsOrderDetail = new ArrayList<GfsOrderDetail>();
        JSONArray orderList = json.getJSONArray("productList");
        for (Object obj : orderList) {
            JSONObject tmp = (JSONObject) obj;
            GfsOrderDetail detail = new GfsOrderDetail();
            detail.setItemId(tmp.getString("itemId"));
            detail.setItemName(tmp.getString("productName"));
            detail.setItemNameEN(tmp.getString("productNameEn"));
            detail.setTransactionId(tmp.getString("transactionId"));
            detail.setSku(tmp.getString("productCode"));
            detail.setOrderQuantity(tmp.getInteger("orderQuantity"));
            detail.setOrderDetailId(tmp.getLong("orderDetailId"));
            if(ValidateUtil.isNotNull(tmp, "quantity"))
            {
                ValidateUtil.validNotNegativeNumber(tmp, "quantity");
                detail.setQuantity(tmp.getInteger("quantity"));
            }
            if(ValidateUtil.isNotNull(tmp, "transactionCurrency")){
                detail.setTransactionCurrency(tmp.getString("transactionCurrency"));
            }
            if(ValidateUtil.isNotNull(tmp, "transactionPrice"))
            {
                ValidateUtil.validNotNegativeNumber(tmp, "transactionPrice");
                ValidateUtil.validatePrecision(tmp, "transactionPrice", 10, 2);
                detail.setTransactionPrice(tmp.getBigDecimal("transactionPrice"));
            }
            if(ValidateUtil.isNotNull(tmp, "goodsLocation")){
                detail.setGoodsLocation(tmp.getString("goodsLocation"));
            }
            listGfsOrderDetail.add(detail);
        }
        gfsOrder.setListGfsOrderDetail(listGfsOrderDetail);
        return gfsOrder;
    }
    
    private Map<String, Object> buildEditOrder(GfsOrder gfsOrder){
        List<GfsOrder> orderList = new ArrayList<GfsOrder>();
        orderList.add(gfsOrder);
        return buildMergeOrderReturn(orderList);
    }
    
    private void validGfsOrderList(RequestMsg requestMsg){
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
//            JSONObject json = (JSONObject) obj;
            //组装参数
            
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
    }
    
    private List<Long> buildOrderIdList(JSONObject json){
    	List<Long> listLong=new ArrayList<Long>();
    	JSONArray orderList = json.getJSONArray("gfsOrderList");
		if(orderList != null && orderList.size() > 0){
		    for (Object obj : orderList) {
	            JSONObject orderID = (JSONObject) obj;
	            if(orderID.containsKey("gfsOrderId")){
	                listLong.add(orderID.getLong("gfsOrderId"));
	            }
	        }
		}
    	return listLong;
    }
    
    private GfsOrderSearchCommand buildSearchCommand(JSONObject json){
        GfsOrderSearchCommand command =new GfsOrderSearchCommand();
        command.setCtx(CommandContext.getContext());
        //组装参数
        Long bpartnerId=Long.valueOf(CommandContext.getContext().getUserId());
        String sellerOrderCode=json.getString("sellerOrderCode");
        String winitOrderCode=json.getString("winitOrderCode");
        String status=json.getString("status");
        String sellerUserId=json.getString("sellerUserId");
        String buyerUserId = json.getString("buyerUserId");
        String saleDateStart = null;
        String saleDateEnd = null;
        String paymentDateStart = json.getString("paymentDateStart");;
        String paymentDateEnd = json.getString("paymentDateEnd");
        String dataType = json.getString("dataType");
        if(StringUtils.isBlank(dataType)){
        	saleDateStart = json.getString("saleDateStart");
        	saleDateEnd = json.getString("saleDateEnd");
        }else if("sold".equalsIgnoreCase(dataType)||"updated".equalsIgnoreCase(dataType)){
        	saleDateStart = json.getString("startDate");
        	saleDateEnd = json.getString("endDate");
        }
        String deliveryDateStart = json.getString("deliveryDateStart");
        String deliveryDateEnd=json.getString("deliveryDateEnd");
        String deliveryWayCode= json.getString("deliveryWayCode");
        String warehouseCode=json.getString("warehouseCode");
        String isError=json.getString("isError");
        String iseBayPlus=json.getString("iseBayPlus");
        String orderType=json.getString("orderType");
        String buyerFullName = json.getString("buyerFullName");
        
        String totalPriceCurrency=json.getString("totalPriceCurrency");
        String transactionCurrency=json.getString("transactionCurrency");
        String totalPriceType=json.getString("totalPriceType");
        String transactionPriceType=json.getString("transactionPriceType");
        Double totalPriceStartPrice=json.getDouble("totalPriceStartPrice");
        Double totalPriceEndPrice=json.getDouble("totalPriceEndPrice");
        Double transactionStartPrice=json.getDouble("transactionStartPrice");
        Double transactionEndPrice=json.getDouble("transactionEndPrice");
        List<Object> itemLocation = json.getJSONArray("itemLocation");
        String eGDorder = json.getString("eGDorder");
        String gddTimeMaxStart = json.getString("gddTimeMaxStart");
        String gddTimeMaxEnd = json.getString("gddTimeMaxEnd");
        if(itemLocation != null && !itemLocation.isEmpty()){
        	command.setItemLocation(itemLocation);
        }
        String winitProductCode = null;
        if(json.containsKey("winitProductCode")){
            winitProductCode = json.getString("winitProductCode");
        }
        if(StringUtils.isNotEmpty(winitProductCode)){
            command.setWinitProductCode(winitProductCode);
        }
        String txStoreKey = null;
        if(json.containsKey("txStoreKey")){
            txStoreKey = json.getString("txStoreKey");
        }
        if(StringUtils.isNotEmpty(txStoreKey)){
            command.setTxStoreKey(txStoreKey);
        }
        List<Object> buyerCountry = json.getJSONArray("buyerCountry");
        if(buyerCountry != null && !buyerCountry.isEmpty()){
        	command.setBuyerCountry(buyerCountry);
        }
        if(null !=bpartnerId){
            command.setBpartnerId(bpartnerId);
        }
        if(StringUtils.isNotEmpty(sellerOrderCode)){
            command.setOrderCode(sellerOrderCode);
        }
        if(StringUtils.isNotEmpty(winitOrderCode)){
            command.setWinitOrderCode(winitOrderCode);
        }
        if(StringUtils.isNotEmpty(status)){
            command.setStatus(status);
        }
        if(!StringUtils.isEmpty(sellerUserId)){
            command.setSellerUserId(sellerUserId);
        }
        if(buyerUserId != null && !buyerUserId.isEmpty()){
            command.setBuyerUserId(buyerUserId);
        }
        if(buyerFullName != null && !buyerFullName.isEmpty()){
        	command.setBuyerFullName(buyerFullName);
        }
        if(null !=saleDateStart){
            saleDateStart += " 00:00:00";
            Date from = DateUtil.parse2Date(saleDateStart, DateUtil.FULL_DATE_STRING);
           command.setSaleDateStart(from);
        }
        if(null != saleDateEnd){
            saleDateEnd += " 23:59:59";
            Date end = DateUtil.parse2Date(saleDateEnd, DateUtil.FULL_DATE_STRING);
            command.setSaleDateEnd(end);
        }
        if(null !=deliveryDateStart){
            deliveryDateStart += " 00:00:00";
            Date from = DateUtil.parse2Date(deliveryDateStart, DateUtil.FULL_DATE_STRING);
           command.setDeliveryDateStart(from);
        }
        if(null !=deliveryDateEnd){
            deliveryDateEnd += " 23:59:59";
            Date end = DateUtil.parse2Date(deliveryDateEnd, DateUtil.FULL_DATE_STRING);
            command.setDeliveryDateEnd(end);
        }
        if(StringUtils.isNotBlank(paymentDateStart)){
            paymentDateStart += " 00:00:00";
            Date from = DateUtil.parse2Date(paymentDateStart, DateUtil.FULL_DATE_STRING);
            command.setPaymentDateStart(from);
        }
        if(StringUtils.isNotBlank(paymentDateEnd)){
            paymentDateEnd += " 23:59:59";
            Date end = DateUtil.parse2Date(paymentDateEnd, DateUtil.FULL_DATE_STRING);
            command.setPaymentDateEnd(end);
        }
        if(StringUtils.isNotEmpty(deliveryWayCode)){
            command.setDeliveryWayCode(deliveryWayCode);
        }
        if(StringUtils.isNotEmpty(warehouseCode)){
            command.setWarehouseCode(warehouseCode);
        }
        if(StringUtils.isNotEmpty(isError)){
            command.setIsError(isError);
        }
        if(StringUtils.isNotEmpty(iseBayPlus)){
            command.setIseBayPlus(iseBayPlus);
        }
        if(StringUtils.isNotEmpty(orderType)){
        	command.setOrderType(orderType);
        }
        if(null != totalPriceType){
        	command.setTotalPriceType(totalPriceType);
        }
        if(null != transactionPriceType){
        	command.setTransactionPriceType(transactionPriceType);
        }
        if(StringUtils.isNotEmpty(totalPriceCurrency)){
        	command.setTotalPriceCurrency(totalPriceCurrency);
        }else{
        	command.setTotalPriceCurrency(null);
        }
        if(StringUtils.isNotEmpty(transactionCurrency)){
        	command.setTransactionCurrency(transactionCurrency);
        }else{
        	command.setTransactionCurrency(null);
        }
        if(null != totalPriceStartPrice){
        	command.setTotalPriceStartPrice(totalPriceStartPrice);
        }
        if(null != totalPriceEndPrice){
        	command.setTotalPriceEndPrice(totalPriceEndPrice);
        }
        if(null != transactionStartPrice){
        	command.setTransactionStartPrice(transactionStartPrice);
        }
        if(null != transactionEndPrice){
        	command.setTransactionEndPrice(transactionEndPrice);
        }
        
        if(StringUtils.isNotEmpty(eGDorder)){
            command.seteGDorder(eGDorder);
        }
        if(null !=gddTimeMaxStart){
            gddTimeMaxStart += " 00:00:00";
            Date from = DateUtil.parse2Date(gddTimeMaxStart, DateUtil.FULL_DATE_STRING);
           command.setGddTimeMaxStart(from);
        }
        if(null != gddTimeMaxEnd){
            gddTimeMaxEnd += " 23:59:59";
            Date end = DateUtil.parse2Date(gddTimeMaxEnd, DateUtil.FULL_DATE_STRING);
            command.setGddTimeMaxEnd(end);
        }
        
        Searchable<?> searchable=buildSearchablePageParams(json);
        String sort=json.getString("sort");
        String sortColumn=json.getString("sortColumn");
        //排序方式
        Direction direction = Direction.DESC;
        if ("asc".equalsIgnoreCase(sort)) {
            direction = Direction.ASC;
        }
        if(StringUtils.isNotEmpty(sort) && StringUtils.isNotEmpty(sortColumn)){
            searchable.addSort(new Sort(direction, sortColumn));
        }
        
        String systemType=json.getString("systemType");
        if(StringUtils.isNotEmpty(systemType)){
            command.setSystemType(systemType);
        }
        if(json.containsKey("platform")){
            command.setPlatform(json.getString("platform"));
        }else{
            command.setPlatform("ebay");
        }
        command.setSearchable(searchable);
        return command;
    }
    
    private GfsOrderAcessRecordCommand acessSearchCommand(JSONObject json){
    	GfsOrderAcessRecordCommand command = new GfsOrderAcessRecordCommand();
    	command.setCtx(CommandContext.getContext());
    	Long bpartnerId=Long.valueOf(CommandContext.getContext().getUserId());
    	String status=json.getString("status");
    	String orderType=json.getString("orderType");
    	String systemType=json.getString("systemType");
    	
        if(StringUtils.isNotEmpty(systemType)){
            command.setSystemType(systemType);
        }
    	if(null !=bpartnerId){
            command.setBpartnerId(bpartnerId);
        }
    	if(StringUtils.isNotEmpty(status)){
            command.setStatus(status);
        }
    	if(StringUtils.isNotEmpty(orderType)){
            command.setOrderType(orderType);
        }else{
        	command.setOrderType(null);
        }
        return command;
    }
   
    
    private void validPullGfsOrder(JSONObject json){
        if (!json.containsKey("ebayAccounts")) {
            throw new ApiException(ErrorCode.FIELD_NOT_NULL, "ebayAccounts");
        }
        if (!json.containsKey("orderDateStart")) {
        	  throw new ApiException(ErrorCode.FIELD_NOT_NULL, "orderDateStart");
        }
        if (!json.containsKey("orderDateEnd")) {
      	  throw new ApiException(ErrorCode.FIELD_NOT_NULL, "orderDateEnd");
        }
      
        
        JSONArray ebaylist = json.getJSONArray("ebayAccounts");
        
        if(ebaylist.size() <= 0){
        	 throw new ApiException(ErrorCode.FIELD_NOT_NULL, "ebayAccount");
        }
        
    }
    
    private void validCreateOutboundOrder(JSONObject json) {
       if(null==json.getBoolean("isException")||!json.getBoolean("isException")){
        // wtWarehouseDeliveryWayId
           ValidateUtil.validNotNull(json, "wtWarehouseDeliveryWayId");
           // wtWarehouseId
           ValidateUtil.validNotNull(json, "wtWarehouseId");
           // isSubmit
           ValidateUtil.validNotNull(json, "isSubmit"); 
       }
        if (!json.containsKey("gfsOrderList")) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "gfsOrderVO");
        }
        JSONArray ebaylist = json.getJSONArray("gfsOrderList");
        if(ebaylist.size() <= 0){
        	 throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "gfsOrderVO");
        }
    }
    
    private void validateCancel(JSONObject json){
    	if (json.containsKey("gfsOrderList")) {
			JSONArray orderList = json.getJSONArray("gfsOrderList");
			for (Object obj : orderList) {
				JSONObject order = (JSONObject) obj;
				ValidateUtil.validNotNull(order, "gfsOrderId");
				ValidateUtil.valid(order, "gfsOrderId", 10, true);
			}
		} else {
			throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "gfsOrderList");
		}
    }
    
    /**
     * 校验isp参数
     * @param json
     * @return
     */
    private void validCreateISPOrder(JSONObject json) {
        
        if(null==json.getBoolean("isException")){
            // winitProductCode  
            ValidateUtil.validNotNull(json, "winitProductCode");
            // warehouseCode
            ValidateUtil.validNotNull(json, "warehouseCode");
            // warehouseCode
            ValidateUtil.validNotNull(json, "dispatchType");
            // warehouseCode
            ValidateUtil.validNotNull(json, "shipperAddrCode");
            //Y：万邑通注册的商品, N：万邑通非注册的商品
            ValidateUtil.validNotNull(json, "productMsg");
            // warehouseCode
            // isSubmit
            ValidateUtil.validNotNull(json, "isSubmit");
        }
        if (!json.containsKey("ebayList")) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "ebayList");
        }
        JSONArray ebaylist = json.getJSONArray("ebayList");
        if(ebaylist.size() <= 0){
             throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "ebayList");
        }
    }

    private BatchSubmitGfsOrderCommand resolveOutboundOrderData(JSONObject json ) {
        BatchSubmitGfsOrderCommand  command  = new BatchSubmitGfsOrderCommand();
        command.setSubmit(buildBooleanValue(json,"isSubmit"));
    	List<GfsOrder> gfsOrders = new ArrayList<GfsOrder>();
        JSONArray gfsOrderList = json.getJSONArray("gfsOrderList");
        for (Object o : gfsOrderList) {
        	GfsOrder gfsOrder = new GfsOrder();
        	gfsOrder.setDeliveryWayCode(json.getString("wtWarehouseDeliveryWayId"));
        	gfsOrder.setWarehouseCode(json.getString("wtWarehouseId"));
        	gfsOrder.setWarehouseName(json.getString("warehouseName"));
        	gfsOrder.setDeliveryWayName(json.getString("deliveryWayName"));
        	JSONObject tobj = (JSONObject) o;
        	gfsOrder.setOrderId(tobj.getLong("gfsOrderId"));
        	buildVasAndAttr(gfsOrder,json);
        	gfsOrder.setNeedMatch(true);
        	gfsOrders.add(gfsOrder);
        }
        command.setOrderType(ApiConstant.ORDER_TYPE_OUTBOUND);//出库单
        command.setGfsOrders(gfsOrders);
        return command;
    }
    
    private void buildVasAndAttr(GfsOrder gfsOrder,JSONObject tobj){
        // vas
        JSONArray vasJsonList = tobj.getJSONArray("vasList");
        if(vasJsonList != null && vasJsonList.size() > 0){
            List<GfsOrderDeliveryVasVo> vasVoList = new ArrayList<GfsOrderDeliveryVasVo>();
            for(Object o1:vasJsonList){
                JSONObject vasJson = (JSONObject) o1;
                GfsOrderDeliveryVasVo vasVo = new GfsOrderDeliveryVasVo();
                vasVo.setServiceCode(vasJson.getString("serviceCode"));
                vasVo.setServiceName(vasJson.getString("serviceName"));
                vasVoList.add(vasVo);
                JSONArray vasAttrVoJsonList = vasJson.getJSONArray("vasAttrList");
                if(vasAttrVoJsonList != null && vasAttrVoJsonList.size() > 0){
                    List<GfsOrderDeliveryVasAttrVo> vasArrtVoList = new ArrayList<GfsOrderDeliveryVasAttrVo>();
                    for(Object o2:vasAttrVoJsonList){
                        JSONObject vasAttrJson = (JSONObject) o2;
                        GfsOrderDeliveryVasAttrVo vasAttrVo = new GfsOrderDeliveryVasAttrVo();
                        vasAttrVo.setAttrKey(vasAttrJson.getString("attrKey"));
                        vasAttrVo.setAttrName(vasAttrJson.getString("attrName"));
                        vasAttrVo.setAttrValue(vasAttrJson.getString("attrValue"));
                        vasArrtVoList.add(vasAttrVo);
                    }
                    vasVo.setVasAttrList(vasArrtVoList);
                }
            }
            gfsOrder.setVasList(vasVoList);
        }
    }
    
    /**
     * 解析isp参数
     * @param json
     * @return
     */
    private BatchSubmitGfsOrderCommand resolveISPOrderData(JSONObject json ) {
        BatchSubmitGfsOrderCommand  command  = new BatchSubmitGfsOrderCommand();
        List<GfsOrder> gfsOrders = new ArrayList<GfsOrder>();
        command.setSubmit(buildBooleanValue(json,"isSubmit"));
        command.setOrderType(ApiConstant.PRODUCT_CATALOG_ISP);
        JSONArray gfsOrderList = json.getJSONArray("ebayList");
        for (Object o : gfsOrderList) {
            JSONObject tobj = (JSONObject) o;
            GfsOrder order = new GfsOrder();
            order.setWinitProductCode(json.getString("winitProductCode"));
            order.setWinitProductName(json.getString("winitProductName"));
            order.setWarehouseCode(json.getString("warehouseCode"));
            order.setWarehouseName(json.getString("warehouseName"));
            order.setShipperAddrCode(json.getString("shipperAddrCode")); 
            order.setProductMsg(json.getString("productMsg"));
            order.setDeliveryWayCode(json.getString("dispatchType"));
            order.setDeliveryWayName(json.getString("dispatchTypeName"));
            order.setOrderId(tobj.getLong("wtEbayOrderId"));
            gfsOrders.add(order);
        }
        command.setGfsOrders(gfsOrders);
        return command;
    }
    
    private boolean buildBooleanValue(JSONObject json,String key){
        return ApiConstant.IS_ACTIVE_Y.equals(json.getString(key)) ? true:false;
    }
    
}
